import {
	setStorage,
	getStorage,
	removeStorage
}
from '@/utils/storage.js'

import {
	login,
	getUserInfo
} from '@/apis/user.js'
export default {
	state() {
		return {
			token: getStorage('token') || null,
			authCode: getStorage('authCode') || null,
			user: getStorage('user') || null,
			permissions: getStorage('user').miniPermissionList || null
		}
	},
	mutations: {
		SET_TOKEN(state, token) {
			state.token = token
		},
		SET_USER(state, user) {
			state.user = user
		},
		SET_AUTHCODE(state, aucthCode) {
			state.aucthCode = aucthCode
		},
		SET_PERMISSIONS(state, permissions) {
			state.permissions = permissions
		}
	},
	actions: {
		async login(state) {
			try {
				//【1】钉钉免登获取authcode
				const res = await dd.getAuthCode()
				state.commit('SET_AUTHCODE', res.authCode)
				setStorage('authCode', res.authCode)
				//【2】登录接口获取用户信息以及token
				const loginRes = await login(res.authCode)
				if (loginRes.code == 0) {
					state.commit('SET_TOKEN', loginRes.data.token)
					state.commit('SET_USER', loginRes.data.user)
					state.commit('SET_PERMISSIONS', loginRes.data.user.miniPermissionList)
					setStorage('token', loginRes.data.token)
					setStorage('user', loginRes.data.user)
				} else {
					return new Promise((resole, reject) => reject(loginRes.errorMessage))
				}
				return new Promise((resole, reject) => resole())
			} catch (err) {
				return new Promise((resole, reject) => reject(err.errorMsg))
			}
		}
	}
}